package dlg.code.producer.s1;

import dlg.code.producer.ItemBuffer;

import java.util.concurrent.TimeUnit;

public class ProducerThread implements Runnable{

    private final ItemBuffer itemBuffer;

    private int len = 10;
    public ProducerThread(ItemBuffer itemBuffer) {
        this.itemBuffer = itemBuffer;
    }

    @Override
    public void run() {
        do {
            synchronized (itemBuffer) {
                while (itemBuffer.isFull()) {
                    System.out.println(Thread.currentThread().getName() + " waiting");
                    try {
                        itemBuffer.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }

                itemBuffer.produce(Thread.currentThread().getName() + " producing " + len--);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                itemBuffer.notifyAll();
            }
        } while (len >= 1);
        System.out.println(Thread.currentThread().getName() + " stop");
    }
}
